import axios from 'axios'
import type { School, SchoolQuery, ApiResponse, PageResult } from '../types/school'

const API_BASE_URL = 'http://41.190.16.58:18088/api'

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应拦截器
apiClient.interceptors.response.use(
  response => response.data,
  error => {
    const message = error.response?.data?.message || '请求出错，请稍后重试'
    return Promise.reject(new Error(message))
  }
)

export const schoolApi = {
  // 添加学校
  addSchool(school: School): Promise<ApiResponse<School>> {
    return apiClient.post('/school/add', school)
  },

  // 查询学校列表（不分页）
  querySchools(params: SchoolQuery): Promise<ApiResponse<School[]>> {
    return apiClient.get('/school/query', { params })
  },

  // 分页查询学校
  querySchoolsByPage(params: SchoolQuery): Promise<ApiResponse<PageResult<School>>> {
    return apiClient.get('/school/page', { params })
  },

  // 更新学校
  updateSchool(school: School): Promise<ApiResponse<School>> {
    return apiClient.put(`/school/update?dsCode=${school.dsCode}`, school)
  },

  // 删除学校
  deleteSchool(id: string, dsCode: string): Promise<ApiResponse<null>> {
    return apiClient.delete('/school/delete', { params: { id, dsCode } })
  },

  // 获取单个学校
  getSchool(id: string, dsCode: string): Promise<ApiResponse<School>> {
    return apiClient.get('/school/query', { 
      params: { id, dsCode }
    }).then(response => {
      const schools = response.data as School[]
      if (schools && schools.length > 0) {
        return {
          code: response.code,
          message: response.message,
          data: schools[0]
        }
      }
      throw new Error('学校不存在')
    })
  }
}